/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.common.filter;

import com.apache.client.IBaseReplaceCard;
import com.apache.client.UctCoreClient;
import com.apache.oscache.OsCacheManager;
import com.apache.passport.common.PassportHelper;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * description:  用户中心客户端filter
 *
 */
public class UctClientFilter extends UctSupperFilter {

    private Logger logger = LoggerFactory.getLogger(UctClientFilter.class);

    private String sessionKey = "loginUser";

    //错误页面地址
    private String errorPage = "";

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) srequest;
        HttpServletResponse response = (HttpServletResponse) sresponse;

        response.setCharacterEncoding("UTF-8");
        response.setDateHeader("expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("pragma", "no-cache");
        request.setCharacterEncoding("UTF-8");
        LoginUser loginUser = null;
        //获取当前访问路径
        String path = request.getServletPath();
        /**监控白名单处理*/
        if(jkWhite(path)){
            chain.doFilter(request, response);
            return;
        }
        //获取cookie值
        String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
        logger.debug(cookieValue);
        //如果cookie为空,则从session中删除用户对象
        if (ToolsUtil.isNull(cookieValue)) {
            boolean isMobile = JudgeIsMoblie(request);
            if (isMobile) {
                String tokenId = request.getParameter("tokenId");
                if ("undefined".equalsIgnoreCase(tokenId))
                    tokenId = "";
                if (ToolsUtil.isNotNull(tokenId)) {
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                clearLoginInfo(request, response);
            }
        } else {
            //通过token及用户名去uc获取用户对象
            loginUser = OsCacheManager.getInstance().getLoginUser(cookieValue);//(LoginUser) request.getSession().getAttribute(sessionKey);
            String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
            if (null == loginUser) {
                if (!cookieValue.startsWith("uni_") && ToolsUtil.isNull(value)) {
                    response.sendRedirect(request.getContextPath() + path);
                    return;
                }
                //value = DesUtils.getInstance().decrypt(value);//解密
                loginUser = UctCoreClient.getLoginUserFromUserCenterSso(StrUtil.doNull(value,""), cookieValue);
                OsCacheManager.getInstance().putLoginUser(cookieValue, loginUser);
//                request.getSession().setAttribute("cookieToken", cookieValue);
            } /*else {
                String tokenId = String.valueOf(request.getSession().getAttribute("cookieToken"));
                if (!cookieValue.equalsIgnoreCase(tokenId)) {//判断是否变更了新用户
                    //String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
                    ///value = DesUtils.getInstance().decrypt(value);
                    loginUser = setLoginUser(request, "");
                }
            }*/
        }

        if (!ToolsUtil.isEmpty(loginUser)) {
            request.getSession().setAttribute(sessionKey, loginUser);//获取session中信息
            if ("T".equals(ToolsUtil.getInstance().getValueByKey("local_user"))) {//用户换证处理操作
                String reflectPath = ToolsUtil.getInstance().getValueByKey("reflect_path");
                try {
                    if (StrUtil.isNotNull(reflectPath)) {
                        Class<?> clazz = Class.forName(reflectPath);
                        IBaseReplaceCard replaceCard = (IBaseReplaceCard) clazz.newInstance();
                        boolean flag = replaceCard
                                .replaceCard(loginUser, request, response);//数据插入到本地，并且换证
                        if (!flag) {
                            response.sendRedirect(request.getContextPath() + "/");
                            return;
                        }
                    }
                } catch (Exception e) {
                    logger.error("换证失败", e);
                }
            }
            Object objRoles = OsCacheManager.getInstance().getCustomerUser(loginUser.getUser().getUserId());
            if (ToolsUtil.isEmpty(objRoles)) {
                List<Role> roles = PBOSSOTools.getRolesForLoginUser(request);//获取用户角色列表
                if (!ToolsUtil.isEmpty(roles)) {
                    request.getSession().setAttribute("loginUserRoles", roles);
                    OsCacheManager.getInstance().putCustomerUser(loginUser.getUser().getUserId(),roles);
                }
            } else {
                request.getSession().setAttribute("loginUserRoles", objRoles);
            }
        }
        //白名单处理
        if (unlockPath(path, sysCode)) {
            chain.doFilter(request, response);
            return;
        }
        if (ToolsUtil.isEmpty(loginUser)) {//退出
            gotoLogin(request,response,"");
            return;
        }

        //只需登录的url地址处理
        String NORIGHT_URL = UctCoreClient.getConf_Map().get("noright_url");
        if (ToolsUtil.isNotNull(NORIGHT_URL)) {
            String str = NORIGHT_URL;
            String[] wus = str.split(",");
            for (int i = 0; i < wus.length; i++) {
                String wurl = wus[i];
                if (ToolsUtil.isNull(wurl)) {
                    continue;
                }
                if (path.startsWith(wurl)) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
        //黑名单处理 ,循环黑名单,只要访问的路径包含黑名单定义,则需要检查,只要检查不通过,则拦截
        if ("1".equals(ToolsUtil.getInstance().getValueByKey("usage_patterns"))) {
            if (!canAccessSupper(loginUser, path)) {//验证访问权限
                gotoLogin(request,response,"对不起,您没有访问权限!!");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    private LoginUser setLoginUser(HttpServletRequest request, String userEname) {
        String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
        LoginUser loginUser = UctCoreClient.getLoginUserFromUserCenterSso(userEname, cookieValue);
        request.getSession().setAttribute("cookieToken", cookieValue);
        OsCacheManager.getInstance().putLoginUser(cookieValue, loginUser);
        return loginUser;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig arg0) throws ServletException {
        sysCode = arg0.getInitParameter("sysCode");
        this.initLincense();
        //资源权限从数据库读取,如果某个资源绑定了对应的权限,则要符合权限判断; 如果没有绑定权限,则默认为登录权限.
        //getSysLock();
        //错误页面地址
        errorPage = StrUtil.doNull(arg0.getInitParameter("errorPage"), "/error.action");
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
    }

    protected boolean jkWhite(String servletPath){
        List<String> whiteJK= PassportHelper.whiteJK;
        for (int i = 0; i < whiteJK.size(); i++) {
            String wurl = whiteJK.get(i);
            if (servletPath.startsWith(wurl)) {
                return true;
            }
        }
        return false;
    }
}
